﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using SangsTools;
using Player;

namespace UI
{
    public class UIBackpack : MonoBehaviour
    {
        public static UIBackpack Ins { get; private set; }

        private Text textOpenClose;
        private bool _isOpen;
        public bool IsOpen
        {
            get => _isOpen;
            set
            {
                _isOpen = value;
                tfScrollViewRoot.DOSizeDelta(new Vector2(_isOpen ? fRootFirstWidth : 0, tfScrollViewRoot.sizeDelta.y), 0.1f);
                textOpenClose.text = _isOpen ? "收起" : "打开";
            }
        }
        private RectTransform tfScrollViewRoot,tfItemRoot;
        private float fRootFirstWidth;

        private PoolComponent<UIBackpackItem> pool;

        private void Awake()
        {
            Ins = this;

            Button openclose = transform.Find("Scroll View/OpenCloseButton").GetComponent<Button>();
            openclose.onClick.AddListener(OnOpenCloseBtnClick);
            textOpenClose = openclose.GetComponentInChildren<Text>();

            tfScrollViewRoot = transform.Find("Scroll View") as RectTransform;
            fRootFirstWidth = tfScrollViewRoot.sizeDelta.x;

            var prefab = GetComponentInChildren<UIBackpackItem>();
            pool = new PoolComponent<UIBackpackItem>(prefab);
            tfItemRoot = prefab.transform.parent as RectTransform;
            prefab.gameObject.SetActive(false);

            IsOpen = true;
        }

        private void Start()
        {
            MyPlayer.Ins.MyBackpack.EventOnItemChange += OnBackpackChange;
            RefreshUI();
        }
        private void OnBackpackChange()
        {
            RefreshUI();
        }
        private void RefreshUI()
        {
            pool.RecycleAll();

            foreach (var item in MyPlayer.Ins.MyBackpack.AllItem)
            {
                pool.GetMember(tfItemRoot).InitUIData(item.Key, item.Value);
            }
        }

        private  void OnOpenCloseBtnClick()
        {
            IsOpen = !IsOpen;
        }
    }
}